<template>
  <FormItem v-bind="formItemProps" :rules="computeRules" :disabled="inputDisabled">
    <template #default>
      <slot>
        <ElSwitch
          active-value="Y"
          inactive-value="N"
          :class="{ 'is-readonly': readonly }"
          :value="value"
          :readonly="readonly"
          :disabled="inputDisabled"
          :placeholder="computePlaceholder"
          v-bind="inputProps"
          v-on="listeners"
          @input="emitInput">
          <template #append>
            <slot name="append"></slot>
          </template>
        </ElSwitch>
      </slot>
    </template>
    <template #error="{ error }">
      <slot name="error" :error="error"></slot>
    </template>
    <template #label>
      <slot name="label"></slot>
    </template>
  </FormItem>
</template>

<script>
  import formInput from './form-input'
  import { Switch } from 'element-ui'
  import { filterProperties, normalizeProps } from '@/util'

  const autoBindKeys = Object.keys(Switch.props).filter(key => !['value', 'placeholder', 'disabled'].includes(key))

  export default {
    name: 'FormSwitch',
    mixins: [formInput],
    props: {
      value: [String, Number, Boolean]
    },
    computed: {
      inputProps() {
        return filterProperties({ ...normalizeProps(this.$attrs), ...this.$props }, autoBindKeys)
      }
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      }
    }
  }
</script>
